"""author: wangxin
   data: 2021/11/24
   project: 王鑫 容器作业.py
"""

# 把日志文件里的ip，时间字段获取出来，时间格式转化为“2021-11-24 12:00:00", 通过ip解析出它属于哪个省份和运营商
# http://ip.aliyun.com/outGetIpInfo?accessKey=alibaba-inc&ip=114.119.156.146

import requests
import json
from datetime import datetime

with open("scwebsite2_ssl.log", "r") as fp:
    for i in fp.readlines():
        a = i.split()[0]  # 截取ip地址
        b = i.split()[3]  # 截取出时间
        c = str(datetime.strptime(b, '[%d/%b/%Y:%H:%M:%S'))  # 格式化输出时间
        url = f"http://ip.aliyun.com/outGetIpInfo?accessKey=alibaba-inc&ip={a}"
        response = requests.get(url)
        d1 = json.loads(response.text)
        with open("result.txt", "a", encoding="utf-8") as fp:
            fp.write(f"IP地址：{a}，访问时间：{c}，运营商为：{d1['data']['isp']}，所在省份为：{d1['data']['region']}\n")
